import {login, getUserInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/token'
import { Message } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    roles: '',
    nickname: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname
    }
  },

  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          if(res.code === 200) {
            setToken(res.token)
            commit('SET_TOKEN', res.token)
            resolve(res)
          } else {
            Message.error(res.msg)
            resolve(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          localStorage.setItem('loginRole', res.data.role)
          commit('SET_ROLES', res.data.role)
          commit('SET_NICKNAME', res.data.nickname)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端登出
    LogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        localStorage.setItem('loginRole', '')
        resolve()
      })
    }
  }
}

export default user
